package com.qingyun.web.security.filter;

import com.alibaba.fastjson.JSON;
import com.qingyun.security.config.TenantContextHolder;
import com.qingyun.security.enums.LoginRole;
import com.qingyun.security.exception.AuthoException;
import com.qingyun.security.model.tiktok.TikTokLoginBody;
import com.qingyun.web.security.token.TikTokAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Classname TikTokLoginAuthenticationFilter
 * @Author dyh
 * @Date 2021/9/8 15:16
 */
public class TikTokLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


	private static String loginUrl="/tiktok/login";

	private AuthenticationManager authenticationManager;

	public TikTokLoginAuthenticationFilter()
	{
		super(new AntPathRequestMatcher(loginUrl, "POST"));
	}

	@Override
	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		super.setAuthenticationManager(authenticationManager);
		this.authenticationManager=authenticationManager;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException {
		String stringFromStream = getStringFromStream(httpServletRequest);
		TikTokLoginBody tikTokLoginBody = JSON.parseObject(stringFromStream, TikTokLoginBody.class);
		//这里这个商户id没用上
		TikTokAuthenticationToken tikTokAuthenticationToken = new TikTokAuthenticationToken(tikTokLoginBody.getCode(), tikTokLoginBody.getShopId());
		Authentication authenticate=null;
		try{
			TenantContextHolder.setTenantType(LoginRole.TIKTOK);
			authenticate = authenticationManager.authenticate(tikTokAuthenticationToken) ;
		} catch (Exception e) {
			e.printStackTrace();
			throw new AuthoException(e.getMessage());
		} finally {
			TenantContextHolder.clearTenantType();
		}
		return authenticate;
	}


	private String getStringFromStream(HttpServletRequest req) {
		ServletInputStream is;
		try {
			is = req.getInputStream();
			int nRead = 1;
			int nTotalRead = 0;
			byte[] bytes = new byte[1024];
			while (nRead > 0) {
				nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
				if (nRead > 0) {
					nTotalRead = nTotalRead + nRead;
				}
			}
			return new String(bytes, 0, nTotalRead, StandardCharsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}

}
